package com.ruowei.modules.sys.service;

import com.ruowei.config.ApplicationProperties;
import com.ruowei.modules.sys.utils.FileUploadUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.UUID;

@Service
@Transactional
public class PhotoUploadService {

    private final String uploadDir;

    public PhotoUploadService(ApplicationProperties applicationProperties) {
        this.uploadDir = applicationProperties.getFile().getUploadDir();
    }

    public String uploadPhoto(byte[] photo, String sufName) throws UnknownHostException {
        String filename;
        if (StringUtils.isEmpty(sufName)) {
            sufName = ".jpg";
            filename = UUID.randomUUID().toString().replace("-", "") + sufName;
        } else {
            filename = UUID.randomUUID().toString().replace("-", "") + sufName.substring(sufName.lastIndexOf("."));//文件名+后缀名
        }
        //获取存放的根目录
        String directory = uploadDir + "/photos/";
        //存放路径

        try {
            if (photo.length <= 204800) { //100k到200k之间

                File file1 = new File(directory + filename);
                File fileParent = file1.getParentFile();
                if (!fileParent.exists()) {
                    fileParent.mkdirs();
                }
                file1.createNewFile();
                FileImageOutputStream imageOutput = null;
                imageOutput = new FileImageOutputStream(file1);
                imageOutput.write(photo, 0, photo.length);
                imageOutput.close();
                return "/photos/" + filename;
            }
            FileUploadUtils.picTOSize(photo, directory + filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/photos/" + filename;
    }
}
